<template>
  <div class="common-view">
    <map-nav>
      <live-trafic></live-trafic>
      <view-notice></view-notice>
      <report-menu></report-menu>
      <map-tools></map-tools>
    </map-nav>
    <map-init></map-init>
  </div>
</template>
<script setup>
import LiveTrafic from '@/components/common/LiveTrafic.vue'
import ViewNotice from '@/components/common/ViewNotice.vue'
import ReportMenu from '@/components/common/ReportMenu.vue'
import MapTools from '@/components/common/MapTools.vue'
import MapInit from '@/components/MapInit.vue'
import MapNav from '@/components/MapNav.vue'

import { onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'

// WebSocket 连接
const socket = new WebSocket('ws://localhost:8080')

// 监听 WebSocket 消息
socket.addEventListener('message', (event) => {
  try {
    const message = JSON.parse(event.data)
    if (message.type === 'userStatusUpdate') {
      const updatedUser = message.user
      // 检查当前用户是否被下线
      const userId = localStorage.getItem('userId')
      // console.log(typeof userId) //string
      // console.log(typeof updatedUser.id) //number
      // 处理强制下线
      if (userId && String(updatedUser.id) === userId && !updatedUser.isOnline) {
        ElMessage.warning('您已被管理员强制下线，请重新登录')
        // 清除本地存储的用户信息
        localStorage.removeItem('token')
        localStorage.removeItem('userId')
        // 跳转到登录页面，强制整个页面重新加载
        window.location.href = '/login'
      }
    }
  } catch (error) {
    console.error('消息解析失败:', error)
  }
})

// 关闭 WebSocket 连接
onUnmounted(() => {
  socket.close()
})
</script>

<style lang="scss" scoped>
.common-view {
  position: relative;
  height: 100vh;

  :deep(.map-nav) {
    position: absolute;
    width: 100vw;
    top: 0;
  }

  :deep(.map-container) {
    position: absolute;
    height: 94vh;
    width: 100vw;
    bottom: 0;
  }
}
</style>
